import Papa from 'papaparse'
import * as FS from 'file-saver'
export function convert(dataJson, options, header) {
  let { transform } = options
  let dataCSV = null
  if (typeof header === 'undefined' || header === '') {
    dataCSV = Papa.unparse(dataJson, options)
  } else {
    var d = {
      fields: Object.values(header),
      data: [],
    }
    for (let i = 0; i < dataJson.length; i++) {
      var a = []
      for (let key in header) {
        if (transform && typeof transform[key] === 'function') {
          const ret = transform[key](dataJson[i], i)
          a.push(ret)
        } else {
          let o = dataJson?.[i] ?? {}
          let result = o?.[key] ?? ''
          a.push(result + '')
        }
      }
      d.data.push(a)
    }
    dataCSV = Papa.unparse(d, options)
  }
  return dataCSV
}

export async function download(filename, dataJson, options, header) {
  let dataCSV = convert(dataJson, options, header)
  filename = `${filename}.csv`
  if (typeof dataCSV === 'undefined' || dataCSV === '') {
    throw new Error('no data')
  }
  const blob = new Blob(['\ufeff', dataCSV], { type: 'text/csv;charset=utf-8' })
  FS.saveAs(blob, filename)
}
